package org.elanfox.intellicommunity.msg.server.base;

import org.apache.poi.util.HexDump;
import org.apache.poi.util.HexRead;

public class CRC16Util {
    public static char crc16Calc(byte[] data_arr, int data_len) {
        char crc16 = 0;
        int i;
        for (i = 0; i < (data_len); i++) {
            crc16 = (char) ((crc16 >> 8) | (crc16 << 8));
            crc16 ^= data_arr[i] & 0xFF;
            crc16 ^= (char) ((crc16 & 0xFF) >> 4);
            crc16 ^= (char) ((crc16 << 8) << 4);
            crc16 ^= (char) (((crc16 & 0xFF) << 4) << 1);
        }
        return crc16;
    }

    public static String crc16Calc(String hexStr, int len) {
        byte[] tt = HexRead.readFromString(hexStr);

        return HexDump.toHex(crc16Calc(tt, tt.length)).substring(8 - len);
    }
}
